package com.thinkcms.security.custom;

import com.thinkcms.core.api.BaseRedisService;
import com.thinkcms.core.config.ThinkCmsConfig;
import com.thinkcms.core.handler.CustomException;
import com.thinkcms.core.utils.ApiResult;
import com.thinkcms.core.utils.Checker;
import com.thinkcms.core.utils.SecurityConstants;
import com.thinkcms.security.license.VerifyLicense;
import com.thinkcms.security.license.VerifyLicenseGenProxy;
import com.thinkcms.security.license.VerifyLicenseImpl;
import com.thinkcms.system.api.system.UserService;
import com.thinkcms.system.dto.system.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @ClassName: MyUserDetailsService
 * @Author: LG
 * @Date: 2019/3/7 11:54
 * @Version: 1.0
 **/
@Component
public class CustomUserLoginRiskCheck {

    @Autowired
    UserService userService;

    @Autowired
    BaseRedisService baseRedisService;

    @Autowired
    ThinkCmsConfig cmsConfig;

    public UserDto loginRiskCheck(String userName) throws CustomException {
        checkMaxError(userName);
        UserDto userDto = null;
        if (Checker.BeNotBlank(userName)) {
            userDto = userService.findUserByUsername(userName);
            if(Checker.BeNotNull(userDto)){
                Set<String> roleSigns = userService.selectRoleSignByUserId(userDto.getId());
                if(Checker.BeNotEmpty(roleSigns)){
                    userDto.setRoleSigns(roleSigns);
                }
            }
        }
        return userDto;
    }


    public void writeErrorLog(String userName) {
        String key = SecurityConstants.ERROR_INPUT_PASS + userName;
        long expireTime = baseRedisService.getExpire(key);
        if (expireTime == -1) {
            baseRedisService.increment(key, 1, 600);
        } else {
            baseRedisService.increment(key, 1);
        }
    }

    private void checkMaxError(String userName) throws CustomException {
        String key = SecurityConstants.ERROR_INPUT_PASS + userName;
        if (baseRedisService.hasKey(key)) {
            Integer times = (Integer) baseRedisService.get(key);
            if (times >= 6) {
                long expireTime = baseRedisService.getExpire(key);
                if (expireTime == -1) {
                    baseRedisService.setExpireTime(SecurityConstants.ERROR_INPUT_PASS + userName, 300L);
                }
                throw new CustomException(ApiResult.result(7001));
            }
        }
    }

    public void checkerLicense() throws Exception {
        try {
            VerifyLicense verifyLicense=(VerifyLicense)VerifyLicenseGenProxy.proxyVerifyLicense(new VerifyLicenseImpl(cmsConfig,baseRedisService));
            verifyLicense.verify(cmsConfig.getLicensePath(),null);
        } catch (Exception e) {
            throw e;
        }
    }
}
